<template>
  <div class="app-container">
    <div v-loading="listLoading" class="control">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="24" :md="15" :lg="15">
          <el-card shadow="hover" class="box-card curr">
            <div v-show="!goods" class="empty">当前暂无拍品开拍</div>
            <div v-if="goods" class="goods">
              <div class="goods-cover">
                <img :src="goods&&goods.cover" alt="">
              </div>
              <div class="goods-info">
                <b>Lot &nbsp;{{ goods.lot }}</b><p>{{ goods.name }}</p>
                <div class="pre-next">
                  <div v-if="goods" class="price">
                    <div style="text-align:left;font-size:14px;margin-bottom: 5px">{{ goods.state === 2 ? '落槌价' : goods.state === 1 && goods.curr_buyer !== '' ? '当前价' : '起拍价' }}:</div>
                    <small :class="goods.state === 2 && goods.final !== '流拍' ? 'green' : ''">￥</small>
                    <b :class="goods.state === 2 && goods.final !== '流拍' ? 'green' : ''">{{ goods.state === 2 ? toThousands(goods.final) : toThousands(goods.curr) }}</b>
                    <el-tag v-if="goods.curr_buyer !== '' && goods.state > 0 && goods.final !== '流拍'" size="mini" type="info">{{ Number(goods.curr_buyer) === 0 ? '现场' : '网络' }}</el-tag>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
          <el-card shadow="hover" class="box-card bid-list">
            <div slot="header" class="clearfix bid-th">
              <div>号牌</div><div>出价</div><div>竞拍者</div><div>操作</div>
            </div>
            <div id="bidlist" ref="bidlist" class="bid-item-box">
              <div v-for="(item, index) in bids" :key="index" class="bid-item">
                <div>{{ item.num }}</div>
                <div>{{ toThousands(item.bid) }}</div>
                <div>{{ item.buyer_way }}</div>
                <div v-if="item.num != '0'">
                  <template v-if="item.type === 'bidnet' && item.pass === undefined">
                    <el-button type="primary" size="mini" icon="el-icon-check" circle @click="passBid(item, index)" />
                    <el-button type="warning" size="mini" icon="el-icon-circle-close" circle @click="denyBid(item, index)" />
                  </template>
                  <span v-if="!item.type || (item.type === 'bidnet' && item.pass)" style="color:#67C23A">已通过</span>
                  <span v-if="item.type === 'bidnet' && item.pass === false" style="color:#F56C6C">已拒绝</span>
                </div>
                <div v-else>-</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <!-- <el-col :xs="24" :sm="24" :md="9" :lg="9">
          <el-card shadow="hover" class="box-card">
            <el-table :data="recent" border fit>
              <el-table-column align="center" prop="lot" label="Lot" width="70" />
              <el-table-column align="center" prop="final" label="落槌价">
                <template slot-scope="scope">{{ toThousands(scope.row.final) }}</template>
              </el-table-column>
              <el-table-column align="center" prop="buyer_way" label="竞拍者" width="70" />
              <el-table-column show-overflow-tooltip align="center" prop="buyer_num" label="号牌" />
            </el-table>
          </el-card>
        </el-col> -->
      </el-row>
    </div>

    <audio ref="audio" :src="mp3" hidden />
  </div>
</template>

<script>
import { getBidnetCurr, passNetBid } from '@/api/ctrl'
import { toThousands } from '@/utils'
export default {
  data () {
    return {
      lotId: '',
      goods: false,
      recent: [],
      listLoading: true,
      bids: [],
      btnLoading: false,
      isSave: false,
      mp3: process.env.VUE_APP_HOST + '/static/music/passbid.mp3'
    }
  },
  created () {
    const id = this.$route.params && this.$route.params.id
    this.lotId = id
    this.fetchData()
    this.initWebSocket()
  },
  mounted () {
    document.addEventListener('visibilitychange', this.handleVisiable)
  },
  destroyed () {
    this.wsSendMsg('leave')
  },
  methods: {
    handleVisiable (e) {
      if (e.target.visibilityState === 'visible') {
        if (!this.global.wsConnected) {
          this.initWebSocket()
        }
      }
    },
    fetchData () {
      this.listLoading = true
      getBidnetCurr(this.lotId).then(res => {
        this.goods = res.data.goods
        this.recent = res.data.recent
        this.bids = res.data.bids.map(el => {
          el.buyer_way = Number(el.num) === 0 ? '现场' : '网络'
          return el
        })
        this.$route.meta.title = `${res.data.name} / 出价拦截`
        this.listLoading = false
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },
    passBid (item, index) {
      item.id = this.goods.id
      passNetBid(item).then(res => {
        item.pass = true
        this.bids.splice(index, 1, item)
      }).catch(err => {
        console.log(err)
      })
    },
    denyBid (item, index) {
      item.pass = false
      this.bids.splice(index, 1, item)
    },
    initWebSocket () {
      const wsData = {
        type: 'join',
        lot_id: this.lotId
      }
      if (this.global.ws) {
        if (this.global.wsConnected) {
          this.global.ws.send(JSON.stringify(wsData))
        }
      } else {
        this.global.ws = new WebSocket(process.env.VUE_APP_WS_HOST)
        this.global.setWs(this.global.ws)
      }
      this.global.ws.onopen = this.wsOnOpen
      this.global.ws.onerror = this.wsOnError
      this.global.ws.onmessage = this.wsOnMessage
      this.global.ws.onclose = this.wsOnClose
    },
    wsOnMessage (e) {
      var data = JSON.parse(e.data)
      // console.log(data)
      const arr = ['willHammer', 'faceLive', 'startAuc', 'cancelAuc', 'dealAuc', 'passAuc', 'reAuc', 'liveBid', 'netBid', 'phoneBid']
      if (Number(data.lot_id) === Number(this.lotId)) {
        switch (true) {
          // 进入、离开专场
          case data.type === 'join' || data.type === 'leave':
            console.log(`${data.uid} ${data.type} 专场 ${this.lotId}`)
            break
          case data.type === 'end':
            console.log(`结束专场 ${this.lotId}`)
            break
          case data.type === 'livePlay':
            console.log(`直播推流：${data.play}`)
            break
          // 更新统计数据
          case data.type === 'count':
            console.log('更新控制台实时统计数据！')
            break
          // 拍品操作客户端广播
          case arr.indexOf(data.type) > -1:
            console.log('客户端广播: ' + data.msg)
            if (data.goods || data.goods === false) {
              this.goods = data.goods
              if (data.type === 'dealAuc' && data.goods.curr_buyer === this.name) {
                this.$message({
                  message: '恭喜您成交！',
                  type: 'success'
                })
              }
            }
            if (data.recent) {
              if (this.recent.length >= 3) {
                this.recent.shift()
              }
              this.recent.push(data.recent)
            }
            if (data.type === 'reAuc' || data.type === 'startAuc') {
              this.bids = []
            }
            break
          // 出价更新出价列表 撤销出价
          case data.type === 'bid' || data.type === 'revoke':
            var { num, bid } = data
            var way = Number(num) === 0 ? '现场' : '网络'
            this.goods.curr = bid
            this.goods.curr_buyer = num
            if (data.type === 'bid') {
              if (way === '网络') {
                this.$refs.audio.play()
              }
              const hasBid = this.bids.some(el => el.num === num && el.bid === bid)
              if (!hasBid) {
                this.bids.unshift({ num, bid, buyer_way: way })
              }
              this.disRevokeBtn = false
            } else {
              this.bids.shift()
            }
            // this.scrollBidList()
            console.log(`${way}出价：${this.toThousands(bid)}`)
            break
          // 网络出价拦截
          case data.type === 'bidnet':
            /* eslint-disable */
            var { num, bid } = data
            var way = Number(num) === 0 ? '现场' : '网络'
            /* eslint-disable */
            this.bids.unshift({ num, bid, buyer_way: way, type: 'bidnet' })
            break
        }
      }
    },
    wsOnOpen () {
      console.log('组件内WebSocket连接成功!')
      this.global.wsConnected = true
      this.wsSendMsg('join')
    },
    wsOnError (e) {
      console.log('组件内WebSocket连接发生错误!')
      this.global.wsConnected = false
    },
    wsOnClose () {
      console.log('组件内WebSocket连接关闭!')
      this.global.wsConnected = false
      this.global.ws = new WebSocket(process.env.VUE_APP_WS_HOST)
      this.global.setWs(this.ws)
    },
    wsSendMsg (type) {
      if (this.global.ws && this.global.wsConnected) {
        var msg = {
          type,
          lot_id: this.lotId
        }
        this.global.ws.send(JSON.stringify(msg))
      }
    },
    toThousands,
    scrollBidList () {
      setTimeout(() => {
        this.$refs.bidlist.scrollTop = this.bids.length * 40 - 30
      }, 0)
    }
  }
}
</script>

<style lang="scss" scoped>
.control {
  width: 100%;
  max-width: 1250px;
  .green {
    color: green !important;
  }
  .box-card {
    margin-bottom: 15px;
    .empty {
      color: #666;
      text-align: center;
      font-size: 14px;
    }
  }
  .curr {
    .goods {
      display: flex;
      &-cover {
        width: 220px;
        max-height: 230px;
        display: flex;
        align-items: center;
        overflow: hidden;
        margin-right: 25px;
        padding: 5px;
        border: 2px solid #333;
        border-radius: 3px;
        img {
          width: 100%;
          height: auto;
        }
      }
      &-info {
        max-height: 300px;
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        p {
          line-height: 1.3;
        }
        .pre-next {
          display: flex;
          margin-bottom: 10px;
          justify-content: space-between;
          align-items: center;
        }
        .btns {
          display: flex;
          flex-wrap: wrap;
          justify-content: space-between;
          // justify-content: flex-start;
          .el-button {
            margin-bottom: 10px;
          }
          .el-button+.el-button {
            margin-left: 0;
          }
        }
      }
    }
    .price-box {
      display: flex;
      justify-content: space-between;
      align-items:center;
      margin-top: 20px;
    }
    .price {
      text-align: center;
      padding: 5px 0 10px;
      small {
        color: firebrick;
        font-size: 14px;
      }
      b {
        font-size: 30px;
        color: rgb(202, 40, 40);
        margin: 0 5px 0 0;
        vertical-align: -3px;
      }
    }
    // .btns {
    //   display: flex;
    //   flex-wrap: wrap;
    //   justify-content: space-around;
    //   .el-button {
    //     margin-bottom: 10px;
    //   }
    // }
  }
  .bid-list {
    .bid-item-box {
      height: 320px;
      overflow-y: scroll;
    }
    .bid-th, .bid-item{
      background: #b8bcc4;
      display: flex;
      text-align: center;
      align-items: center;
      div {
        height: 52px;
        padding: 12px 0;
        border-right: 1px solid #eee;
        flex: 1;
        line-height: 26px;
        &:first-of-type {
          width: 30%;
          padding: 12px 4px;
        }
        // &:last-of-type {
        //   width: 25%;
        //   border-right: none;
        // }
        // &:nth-of-type(2) {
        //   flex: 1;
        // }
      }
    }
    .bid-item {
      color: #606266;
      font-size: 14px;
      background: #fff;
      border-bottom: 1px solid #eee;
      &:last-of-type {
        border: none;
      }
      div {
        padding: 12px 0;
        border-right: none;
      }
    }
  }
  .bid-area {
    .input-box {
      width: fit-content;
      margin: 0 auto 20px;
      .el-input {
        width: 100%;
        margin: 10px 14px 10px 0;
      }
      .el-radio-group {
        margin: 10px 10px 0 0px;
      }
      .input-btn {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
    }
    .bid-add {
      text-align: center;
      .el-radio {
        width: 100px;
        margin-bottom: 15px;
      }
    }
  }
  .lot-info {
    .lot-name {
      margin-bottom: 10px;
      span {
        margin-right: 10px;
      }
    }
    .lot-live {
      display: flex;
      margin: 15px 0 0;
      width: 470px;
      align-items: center;
      .el-button {
        width: 60px;
        margin: 0 10px;
        display: block;
      }
      img {
        width: 24px;
        height: 100%;
        border-radius: 10%;
        display: block;
      }
    }
    .lot-num {
      font-size: 14px;
      line-height: 1.5;
      &:nth-of-type(3) {
        margin-top: 15px;
      }
      span {
        margin-right: 20px;
      }
    }
  }
}
</style>
<style lang="scss">
.control {
  .el-card__header {
    padding: 15px;
    font-weight: bold;
  }
  .el-card__body {
    padding: 15px;
  }

  .bid-list {
    .el-card__header {
      padding: 0;
    }
    .el-card__body {
      padding: 0;
    }
  }
  .goods-list {
    .el-table--medium td, .el-table--medium th {
      padding: 6px 0;
      cursor: pointer;
    }
    td.goods-name-td .cell {
      color: rgb(81, 81, 206);
      text-decoration: underline;
    }
    .el-table .dis-row {
      background: #f0f9eb;
    }
  }
  .el-input.is-disabled .el-input__inner {
    background: #fff;
    color: #606266;
  }
}
</style>
